/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2023-03-10     dreamcmi       the first version
 */

#include "another_encrypt.h"

uint8_t *key[8];

uint8_t g_key[16] = {0};
uint8_t g_mode = ANE_AES_ECB;
uint8_t g_ende_mode = ANE_ENCRYPT;

uint8_t key1[16] = {0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18,0x19,0x1A,0x1B,0x1C,0x1D,0x1E,0x1F,0x20};
uint8_t key2[16] = {0x12,0x12,0x13,0x14,0x15,0x16,0x17,0x18,0x19,0x1A,0x1B,0x1C,0x1D,0x1E,0x1F,0x20};
uint8_t key3[16] = {0x13,0x12,0x13,0x14,0x15,0x16,0x17,0x18,0x19,0x1A,0x1B,0x1C,0x1D,0x1E,0x1F,0x20};
uint8_t key4[16] = {0x14,0x12,0x13,0x14,0x15,0x16,0x17,0x18,0x19,0x1A,0x1B,0x1C,0x1D,0x1E,0x1F,0x20};
uint8_t key5[16] = {0x15,0x12,0x13,0x14,0x15,0x16,0x17,0x18,0x19,0x1A,0x1B,0x1C,0x1D,0x1E,0x1F,0x20};
uint8_t key6[16] = {0x16,0x12,0x13,0x14,0x15,0x16,0x17,0x18,0x19,0x1A,0x1B,0x1C,0x1D,0x1E,0x1F,0x20};
uint8_t key7[16] = {0x17,0x12,0x13,0x14,0x15,0x16,0x17,0x18,0x19,0x1A,0x1B,0x1C,0x1D,0x1E,0x1F,0x20};
uint8_t key8[16] = {0x18,0x12,0x13,0x14,0x15,0x16,0x17,0x18,0x19,0x1A,0x1B,0x1C,0x1D,0x1E,0x1F,0x20};

mbedtls_aes_context context;

void ane_init()
{
    key[0] = key1;
    key[1] = key2;
    key[2] = key3;
    key[3] = key4;
    key[4] = key5;
    key[5] = key6;
    key[6] = key7;
    key[7] = key8;
    mbedtls_aes_init(&context);
}

void ane_deinit()
{
    mbedtls_aes_free(&context);
}

int ane_set_key(uint8_t id)
{
    if (id > 8) {
        return -1;
    }
    memcpy(g_key, key[id-1], 16);
    mbedtls_aes_setkey_enc(&context, g_key, 16 * 8);
    mbedtls_aes_setkey_dec(&context, g_key, 16 * 8);
    return 0;
}

int ane_set_aes_mode(uint8_t id)
{
    if (id > 2) {
        return -1;
    }
    g_mode = id;
    return 0;
}

int ane_set_ende_mode(uint8_t id)
{
    if (id > 2) {
        return -1;
    }
    g_ende_mode = id;
    return 0;
}

int ane_encrypt(uint8_t *in, uint8_t *out)
{
    if (g_mode == ANE_AES_ECB) {
        return mbedtls_aes_crypt_ecb(&context, MBEDTLS_AES_ENCRYPT, in, out);
    }else if (g_mode == ANE_AES_CBC) {
        return -1;
    }else {
        return -1;
    }
}

int ane_decrypt(uint8_t *in, uint8_t *out)
{
    if (g_mode == ANE_AES_ECB) {
        return mbedtls_aes_crypt_ecb(&context, MBEDTLS_AES_DECRYPT, in, out);
    }else if (g_mode == ANE_AES_CBC) {
        return -1;
    }else {
        return -1;
    }
}

void dump_mode()
{
    if (g_mode == ANE_AES_ECB) {
        rt_kprintf("MODE:AES128 ECB\n");
    }else if (g_mode == ANE_AES_CBC) {
        rt_kprintf("MODE:AES128 CBC\n");
    }else {
        rt_kprintf("MODE err %d\n", g_mode);
    }
}

void dump_key()
{
    for(uint8_t i=0; i<16; i++)
    {
        rt_kprintf("%02x ",g_key[i]);
    }
    rt_kprintf("\n");
}
